package main

import (
	"fmt"
	"gitee.com/DevilYyx/common"
	base2 "gitee.com/DevilYyx/go-paas/internal/base/domain/service"
	"gitee.com/DevilYyx/go-paas/internal/base/proto/base"
	"gitee.com/DevilYyx/go-paas/public"
	hystrix2 "gitee.com/DevilYyx/go-paas/public/plugin/hystrix"
	"github.com/afex/hystrix-go/hystrix"
	"github.com/asim/go-micro/plugins/registry/consul/v3"
	ratelimit "github.com/asim/go-micro/plugins/wrapper/ratelimiter/uber/v3"
	opentracing2 "github.com/asim/go-micro/plugins/wrapper/trace/opentracing/v3"
	"github.com/asim/go-micro/v3"
	"github.com/asim/go-micro/v3/registry"
	"github.com/opentracing/opentracing-go"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"net"
	"net/http"
)

func main() {
	//1.注册中心
	consul := consul.NewRegistry(func(options *registry.Options) {
		options.Addrs = []string{
			//如果放到docker-compose 也可以是服务名称
			"127.0.0.1:8500",
		}
	})

	// 配置中心
	consulConfig, err := common.GetConsulConfig("localhost", 8500, "/micro/config")
	if err != nil {
		log.Fatal(err)
	}

	// 使用配置中心连接mysql
	mysqlInfo, err := common.GetMysqlFromConsul(consulConfig, "mysql")
	if err != nil {
		log.Fatal(err)
	}
	dsn := fmt.Sprintf("%s:%s@%s", mysqlInfo.User, mysqlInfo.Password, mysqlInfo.Url)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}
	s, err := db.DB()
	defer s.Close()
	fmt.Println("数据库连接成功")

	//4.添加链路追踪
	t, io, err := common.NewTracer("devil-base", "localhost:6831")
	if err != nil {
		log.Fatal(err)
	}
	defer io.Close()
	opentracing.SetGlobalTracer(t)

	// 5.创建熔断器
	hystrixHandler := hystrix.NewStreamHandler()
	hystrixHandler.Start()

	go func() {
		err = http.ListenAndServe(net.JoinHostPort("0.0.0.0", "9092"), hystrixHandler)
		if err != nil {
			log.Fatal(err)
		}
	}()
	// 创建服务
	service := micro.NewService(
		micro.Name("devil-base"),
		micro.Version("1.0"),
		// 添加注册中心
		micro.Registry(consul),
		micro.WrapHandler(opentracing2.NewHandlerWrapper(opentracing.GlobalTracer())),
		micro.WrapClient(opentracing2.NewClientWrapper(opentracing.GlobalTracer())),
		micro.WrapClient(hystrix2.NewClientHystrixWrapper()),
		// 添加限流
		micro.WrapHandler(ratelimit.NewHandlerWrapper(1000)),
		micro.WrapClient(ratelimit.NewClientWrapper(1000)),
	)

	//7.添加监控
	common.PrometheusBoot(9200)

	// 初始化服务
	service.Init()

	// 注册接口
	_ = base.RegisterBaseHandler(service.Server(), &base2.Service{
		Service: public.GetBaseService(),
	})

	// 启动服务
	if err := service.Run(); err != nil {
		//输出启动失败信息
		log.Fatal(err)
	}
}
